#!/bin/bash
_command_exists() {
    for c in "$@"; do
        command -v "$c"
    done
}

_check_sudo() {
    [[ "$check_sudo_flag" -eq 1 ]] && return 0
    if [ "$USER" != "root" ]; then
        if sudo -l -U "$USER"; then
            pre_sudo="sudo"
        else
            echo "User $USER has no permission to execute this script!"
            echo "Please run visudo with root, and set sudo to $USER"
            return 1
        fi
    fi
    if _command_exists apt; then
        cmd="$pre_sudo apt"
	$cmd update &>/dev/null
    elif _command_exists yum; then
        cmd="$pre_sudo yum"
        $cmd install epel-release
    elif _command_exists dnf; then
        cmd="$pre_sudo dnf"
    else
        echo -e "not found apt/yum/dnf, exit 1"
        return 1
    fi
    check_sudo_flag=1
}
_check_dependence(){
    $cmd install -y sshpass
}
main(){
if [[ $# -ne 2 && $1 != "-h" ]]
then
    echo "请输入源目录路径和目标目录路径！"
    exit 1
fi
if [[ $1 == "-h" ]]
then
    echo -e "case:\n"
    echo -e "\tbash ssh-copy.sh <source_path> <target_path>\n"
    echo -e "\tbash ssh-copy.sh /home/ops/1.txt /home/ops/1.txt\n"
    exit
fi
_check_sudo
_check_dependence
#user_home_path=/root
#user_name=root

user_home_path=/home/ops
user_name=ops
ip_list="
192.168.1.110
192.168.1.178
"
 
echo '==============创建ssh-keygen=============='

ssh-keygen -f $user_home_path/.ssh/id_rsa -P ''
 
echo '==============分发 pub key=============='
 
for ip in   $ip_list
do
    sshpass -pflyh6 ssh-copy-id -i $user_home_path/.ssh/id_rsa.pub  -o  StrictHostKeyChecking=no $user_name@$ip 
done

for n in $ip_list
do
   scp -P 22 -rp $1 $user_name@$n:$2 &>/dev/null
   #如果返回值等于0则执行下面的命令
   if [ $? -eq 0  ]
   then
	    echo -e "$n successful"
   else
            echo -e "$n failure"
   fi
done
}
main "$@"
